package wassalt.Services;

import static wassalt.Utils.AppConstants.*;

import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class HTTPService extends IntentService {

	public HTTPService() {
		super("Hello");
		// TODO Auto-generated constructor stub
	}

	/**
	 * Executes HTTP requests and broadcasts an intent containing a String
	 * representing the HTTP response, the HTTP response string key in the
	 * broadcasted intent is <code>HTTP_RESPONSE</code> string defined in
	 * <code>AppConstants</code> class, so to get it just use: String
	 * responseStr = intent.getExtras().getString(HTTP_RESPONSE);The action of
	 * the broadcasted intent is the same as the action in the intent parameter
	 * passed (<code>intent</code>). So each activity should have something
	 * like: final String HTTP_<This_Activity>_FILTER="blabla"; and add this
	 * string in the service intent like the following:
	 * serviceIntent.add(FILTER,HTTP_<This_Activity>_FILTER); FILTER is a string
	 * constant defined in AppConstants class.
	 * 
	 * @author loai
	 * @param intent
	 *            the intent passed from the caller activity
	 */

	@Override
	protected void onHandleIntent(Intent intent) {
		String url = intent.getExtras().getString(URL);
		intent.removeExtra(URL);
		Log.e("URL", url);
		Bundle extras = intent.getExtras();
		if (extras != null) {
			Log.e("Extras", extras.toString());
			Set<String> extrasKeys = extras.keySet();
			if (!extrasKeys.isEmpty()) {
				url += "?";
				for (String key : extrasKeys)
					url += (key + "=" + extras.get(key) + "&");
				
				url = url.substring(0, url.length() - 1);
			}
		}
		DefaultHttpClient client = new DefaultHttpClient();
		HttpResponse resp = null;
		// Get the filter assigned to the intent from the caller activity
		String action = intent.getAction();
		// Assign the filter to the broadcast intent
		Intent broadCastIntent = new Intent(action);
		try {
			Log.e(HTTPService.class.getName(), url);
			resp = client.execute(new HttpGet(url));
			String responseString = EntityUtils.toString(resp.getEntity());
			// Add the response to the intent
			broadCastIntent.putExtra(HTTP_RESPONSE, responseString);
			Log.e(HTTPService.class.getName(), responseString);
		} catch (Exception e) {
			Log.e(HTTPService.class.getName(), "Error " + e.getMessage());
		} finally {
			// Add the status of the HTTP request
			int httpCode = resp == null ? HttpStatus.SC_NOT_FOUND : resp
					.getStatusLine().getStatusCode();
			broadCastIntent.putExtra(HTTP_STATUS, httpCode);
			// Add the parameters sent from the caller activity back to it
			broadCastIntent.putExtras(intent);
		}
		sendOrderedBroadcast(broadCastIntent,null);
	}
}
